//
//  MCMyCommissionViewController.swift
//  StoreManage
//
//  Created by MC on 2018/1/30.
//  Copyright © 2018年 MC. All rights reserved.
//

import UIKit

class MCMyCommissionViewController: MCViewController {

    public var clerkId = 0
    private var pageNumber = 1
    private var currentDateStr = ""
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        baseSetting()
        
        initUI()
        
        
        let formmater = DateFormatter.init()
        formmater.dateFormat = "yyyy-MM"
        currentDateStr = formmater.string(from: Date.init())
        sendNetworking(time: currentDateStr)
    }
    

    // MARK: - Setter & Getter
    lazy private var tableView: MCTableView = {
        let tableView = MCTableView.init(frame: CGRect.zero, style: UITableViewStyle.plain)
        tableView.delegate = self
        tableView.dataSource = self
        return tableView
    }()
    
    lazy var dataArrayM: NSMutableArray = {
        let arrayM = NSMutableArray()
        return arrayM
    }()
    
    lazy var headView: MCMyCommissionHeaderView = {
        let view = MCMyCommissionHeaderView()
        view.calendarButton.addTarget(self, action: #selector(calendarButtonClicked), for: UIControlEvents.touchUpInside)
        view.timeButton.addTarget(self, action: #selector(calendarButtonClicked), for: UIControlEvents.touchUpInside)

        return view
    }()
    
    lazy var popUpDateView: MCDatePickerPopupView = {
        let view = MCDatePickerPopupView()
        view.cancelButton.backgroundColor = UIColor.MCBlue
        view.sureButton.backgroundColor = UIColor.MCBlue
        
        view.pickerView.datePickerClosure = { timeStr in
            self.headView.timeButton.nameLabel.text = timeStr
        }
        view.pickerView.maximumDate = Date.init()
        view.pickerView.settingPickerView(mode: MCDateMode.year_month)
        
        return view
    }()
}
//MARK: 通知回调，闭包回调，点击事件
extension MCMyCommissionViewController {
    @objc func calendarButtonClicked() {
        
        let dateStr = headView.timeButton.nameLabel.text ?? ""
        
        
        popUpDateView.pickerView.maximumDate = Date.init()
        popUpDateView.pickerView.defaultDate = MCDateManager_getDateFromString(dateStr, dateFormat: "yyyy-MM")
        popUpDateView.pickerView.settingPickerView(mode: MCDateMode.year_month)
        
        
        view.window?.addSubview(popUpDateView)
        popUpDateView.snp.remakeConstraints { (make) ->Void in
            make.edges.equalTo(view.window!)
        }
    }
}


//MARK: 网络请求
extension MCMyCommissionViewController {
    func sendNetworking(time:String) {
        
        headView.timeButton.nameLabel.text = time
        
        let para = [
            "dateMonth" : time,
            "inquirer"  : clerkId,
            "pageNum"   : pageNumber,
            "pageSize"  : 10,
            ] as [String : Any]
        
        MCNetwork.POST(JAVA_getMyJournal, para, vc: self, success: { (data) in
            
            self.tableView.mj_header.endRefreshing()
            self.tableView.mj_footer.endRefreshing()
            
            if self.pageNumber == 1 {
                self.dataArrayM.removeAllObjects()
                self.tableView.mj_footer.resetNoMoreData()
            }
            
            let dataDict = data.dictionaryObject ?? [:]
            self.headView.dataDict = dataDict

            
            // 列表
            let dataArray = dataDict["myJournalList"] as? NSArray ?? []
            
            if dataArray.count == 0 {
                self.tableView.mj_footer.endRefreshingWithNoMoreData()
            }
            
            if self.dataArrayM.count + dataArray.count == 0 {
                self.tableView.showBgImage()
            } else {
                self.tableView.hideBgImage()
                
                for dict in dataArray {
                    let tempDict = dict as? [String:Any] ?? [:]
                    let model = MCMyCommissionModel()
                    model.setValuesForKeys(tempDict)
                    self.dataArrayM.add(model)
                }
            }
            self.tableView.reloadData()

            
        }, failure: nil)
    }

}

//MARK: UI的处理,通知的接收
extension MCMyCommissionViewController {
    func baseSetting() {
        self.title = "我的佣金"
        self.view.backgroundColor = UIColor.white
        self.tableView.mj_header = MCRefreshHeader.init(refreshingBlock: {
            self.pageNumber = 1
            self.sendNetworking(time: self.currentDateStr)
        })
        
        self.tableView.mj_footer = MCRefreshFooter.init(refreshingBlock: {
            self.pageNumber += 1
            self.sendNetworking(time: self.currentDateStr)
        })
    }
    
    func initUI() {
        view.addSubview(tableView)
        tableView.snp.remakeConstraints { (make) ->Void in
            make.edges.equalTo(view).inset(UIEdgeInsetsMake(0, 0, CGFloat(MCSafeAreaBottomHeight), 0))
        }
        tableView.tableHeaderView = headView
    }
}



extension MCMyCommissionViewController : UITableViewDelegate,UITableViewDataSource {
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.dataArrayM.count
    }
    

    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 70
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let cell = MCMyCommissionCell.init(style: UITableViewCellStyle.value1, reuseIdentifier: "cell")
        cell.selectionStyle = UITableViewCellSelectionStyle.none
        
        if indexPath.row % 2 == 0 {
            cell.backgroundColor = UIColor.MCGray_light
        } else {
            cell.backgroundColor = UIColor.white
        }
        
        cell.model = self.dataArrayM[indexPath.row] as! MCMyCommissionModel
        return cell
    }
}

extension MCMyCommissionViewController : MCYearAndMonthPickerViewDelegate {
    func MCYearAndMonthPickerViewSelectedRow(str: String) {
        self.pageNumber = 1
        currentDateStr = str
        self.sendNetworking(time: currentDateStr)
    }
}

